package models

import (
	"errors"
	"time"

	"github.com/astaxie/beego/orm"
)

type Coin struct {
	Id       int
	Type     int
	Symbol   string
	Contract string
	Fee      float64
	Last     int
}

func init() {
	orm.RegisterModel(new(Coin))
}

//添加币种信息
func ORMAddCoin(Symbol, Contract string, Fee float64, Type int) error {
	var coin0 Coin

	o := orm.NewOrm()
	o.QueryTable("Coin").Filter("Symbol", Symbol).One(&coin0)
	if coin0.Id != 0 {
		return errors.New("添加失败,币种信息已存在")
	}
	coin := new(Coin)
	coin.Type = Type
	coin.Contract = Contract
	coin.Symbol = Symbol
	coin.Fee = Fee
	coin.Last = int(time.Now().Unix())

	_, err := o.Insert(coin)
	return err
}

//更新币种矿工费
func ORMUpdateFee(Id int, Fee float64) error {
	coin := new(Coin)
	coin.Id = Id

	o := orm.NewOrm()
	o.Read(coin)
	if coin.Symbol != "" {
		coin.Fee = Fee
		coin.Last = int(time.Now().Unix())
		_, err := o.Update(coin)
		if err != nil {
			return errors.New("更改失败,报错" + err.Error())
		}
		return nil
	}
	return errors.New("更改失败,币种信息不存在")
}

//删除币种信息
func ORMDelCoin(Id int) error {
	o := orm.NewOrm()
	coin := new(Coin)
	coin.Id = Id
	o.Read(coin)
	if coin.Symbol != "" {

		_, err := o.Delete(coin)
		if err != nil {
			return errors.New("删除失败,报错" + err.Error())
		}
		return nil
	}
	return errors.New("删除失败,币种信息不存在")
}

//获取矿工费,合约地址
func ORMGetCoinFeeContract(Symbol string) (string, float64, error) {
	var coin0 Coin

	o := orm.NewOrm()
	o.QueryTable("Coin").Filter("Symbol", Symbol).One(&coin0)
	if coin0.Id == 0 {
		return "", 0, errors.New("获取矿工费出错")
	}

	return coin0.Contract, coin0.Fee, nil
}

//获取Symbol类型
func ORMGetCoinType(Symbol string) (int, error) {
	var coin0 Coin

	o := orm.NewOrm()
	o.QueryTable("Coin").Filter("Symbol", Symbol).One(&coin0)
	if coin0.Id == 0 {
		return 0, errors.New("获取币种类型出错出错")
	}

	return coin0.Type, nil
}

//获取币种列表
func ORMListCoin() ([]Coin, error) {
	var allcoin []Coin
	o := orm.NewOrm()
	o.QueryTable("Coin").All(&allcoin)

	for k, _ := range allcoin {
		allcoin[k].Fee = float64(allcoin[k].Fee)
	}

	return allcoin, nil

}

//获取币种列表
func ORMListCoinByType(Type int) ([]Coin, error) {
	var allcoin []Coin
	o := orm.NewOrm()
	o.QueryTable("Coin").Filter("Type", Type).All(&allcoin)

	return allcoin, nil

}
